package kortmann.rene.leo.factories;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import kortmann.rene.leo.model.LEO;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

 public class LeoFactory 
{
	public static LEO GetLeoFromJson(String inJson)
	{
		LEO result = null;
		
		try
		{
			result = new LEO();
			
			JSONParser parser = new JSONParser();
			
			JSONObject obj = (JSONObject)parser.parse(inJson);
			
			for(Method curMethod : LEO.class.getMethods())
			{
				for(Annotation curAnno : curMethod.getAnnotations())
				{
					if(curAnno instanceof JsonObjectSet)
					{
						JsonObjectSet jo = (JsonObjectSet)curAnno;
						
						if(obj.containsKey(jo.path()) && (String)obj.get(jo.path()) != null && !(((String)obj.get(jo.path())).equals("null")))
						{
							curMethod.invoke(result, obj.get(jo.path()));
						}
					}
				}
			}			
		}
		catch(Exception ex)
		{
			result = null;
		}
		
		return result;
	}
	
	public static String getJsonFromLeo(LEO inLeo)
	{
		String result = null;
		
		if(inLeo == null)
			return result;
		
		JSONObject obj=new JSONObject();
		
		for(Method cur : LEO.class.getDeclaredMethods())
		{
			for(Annotation curAnno : cur.getAnnotations())
			{
				if(curAnno instanceof JsonObjectGet)
				{
					JsonObjectGet jo = cur.getAnnotation(JsonObjectGet.class);
					
					if(cur.getReturnType() == String.class)
					{
						
						try 
						{
							String value = (String)cur.invoke(inLeo, null);
							
							if(value != null && value.length() > 0 && value != "null")
								obj.put(jo.path(), value);
						} 
						catch (IllegalAccessException e) 
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
						catch (IllegalArgumentException e) 
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						catch (InvocationTargetException e) 
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}						
					}
				}
			}
		}
		
		result = obj.toJSONString();
		
		return result;
	}
}
